package com.xinlang.excel.io;


import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;

import net.sf.json.JSONNull;
import net.sf.json.JSONObject;

import org.apache.hadoop.io.Writable;

import com.xinlang.excel.Table;


public class TableWrapper extends Table implements Writable {

	Table table = null;

	public TableWrapper() {
		this.table = new Table();
	}

	public TableWrapper(Table table) {
		this.table = table;
	}

	public Table getTable() {
		return table;
	}

	@Override
	public void readFields(DataInput in) throws IOException {
		int size = in.readInt();
		for(int i = 0; i<size; i++){			
			String x = in.readUTF();
			String jsonString = in.readUTF();
			JSONObject json = JSONObject.fromObject(jsonString);
			for (Object key : json.keySet()) {
				Object value = json.get(key);
				if(value instanceof JSONNull){
					table.put(x, key.toString(), null);
				}else{					
					table.put(x, key.toString(), value);
				}
			}
		}
	}

	@Override
	public void write(DataOutput out) throws IOException {
		int size = table.getSize();
		out.writeInt(size);
		for (Map.Entry<String, Map<String, Object>> row : table.getRows().entrySet()) {
			String x = row.getKey();
			String json = JSONObject.fromObject(row.getValue()).toString();
			out.writeUTF(x);
			out.writeUTF(json);
		}
	}

}
